/**
 * 
 */
package com.maywide.jdp.system.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.maywide.jdp.core.exception.AppException;
import com.maywide.jdp.core.vo.Context;
import com.maywide.jdp.core.vo.Page;
import com.maywide.jdp.system.annotation.JSON;
import com.maywide.jdp.system.bean.BusinessFunctionBean;
import com.maywide.jdp.system.entities.BusinessFunction;
import com.maywide.jdp.system.entities.Module;
import com.maywide.jdp.system.entities.Role;
import com.maywide.jdp.system.entities.Rule;
import com.maywide.jdp.system.utils.JSONEditor;
import com.maywide.jdp.system.vo.ModuleBusinessFunctionTree;

/**
 * 业务模块管理Service
 * 
 * @author luoyang
 * @version 1.0
 * @since JDK1.6
 */
@Controller("businessFunctionService")
public class BusinessFunctionServiceImpl implements BusinessFunctionService {
	public static final String APP_TYPE_BASE = "base";
	public static final String APP_TYPE_ROLES = "roles";
	public static final String APP_TYPE_RULES = "rules";

	/**
	 * 业务模块管理Bean接口
	 */
	private BusinessFunctionBean bean = null;

	/**
	 * @param bean
	 *            the bean to set
	 */
	@Autowired
	@Qualifier("businessFunctionBean")
	public void setBean(BusinessFunctionBean bean) {
		this.bean = bean;
	}

	@JSON
	@RequestMapping("/system/function/insert.json")
	@Override
	public BusinessFunction insert(
			@RequestParam(value = "businessFunction") BusinessFunction businessFunction,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.insert(businessFunction);
		return businessFunction;
	}

	@JSON
	@RequestMapping("/system/function/update.json")
	@Override
	public BusinessFunction update(
			@RequestParam(value = "businessFunction") BusinessFunction businessFunctionVO,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		String id = businessFunctionVO.getId();
		BusinessFunction businessFunction = (BusinessFunction) bean.load(id);

		// 取得不可改变属性
		Module module = businessFunction.getModule();

		businessFunctionVO.setModule(module);
		BeanUtils.copyProperties(businessFunctionVO, businessFunction);

		bean.update(businessFunction);

		return businessFunction;
	}

	@JSON
	@RequestMapping("/system/function/updateApp.json")
	@Override
	public BusinessFunction updateApp(
			@RequestParam(value = "businessFunction") BusinessFunction businessFunctionVO,
			@RequestParam(value = "appType") String appType,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		String id = businessFunctionVO.getId();

		if (appType.equals(APP_TYPE_BASE)) {
			// 取得不可改变属性
			BusinessFunction businessFunction = (BusinessFunction) bean
					.load(id);
			Module parent = businessFunction.getModule();
			List<Rule> rules = businessFunction.getRules();

			businessFunctionVO.setModule(parent);
			businessFunctionVO.setRules(rules);
			BeanUtils.copyProperties(businessFunctionVO, businessFunction);

			bean.update(businessFunction);
			return businessFunction;
		} else if (appType.equals(APP_TYPE_ROLES)) {
			List<Role> roles = businessFunctionVO.getRoles();
			BusinessFunction businessFunction = (BusinessFunction) bean
					.load(id);
			businessFunction.setRoles(roles);
			bean.update(businessFunction);
			return businessFunction;
		} else if (appType.equals(APP_TYPE_RULES)) {
			List<Rule> rules = businessFunctionVO.getRules();
			BusinessFunction businessFunction = (BusinessFunction) bean
					.load(id);
			businessFunction.setRules(rules);
			bean.update(businessFunction);
			return businessFunction;
		} else {
			throw new AppException("未知的应用类型!");
		}
	}

	@JSON
	@RequestMapping("/system/function/load.json")
	@Override
	public BusinessFunction load(@RequestParam(value = "id") String id,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		BusinessFunction businessFunction = null;
		businessFunction = (BusinessFunction) bean.load(id);
		return businessFunction;
	}

	@RequestMapping("/system/function/lock.json")
	@Override
	public void lock(@RequestParam(value = "id") String id,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.lock(id);
	}

	@RequestMapping("/system/function/unlock.json")
	@Override
	public void unlock(@RequestParam(value = "id") String id,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.unlock(id);
	}

	@RequestMapping("/system/function/move.json")
	@Override
	public void move(@RequestParam(value = "ids") List<String> ids,
			@RequestParam(value = "targetID") String targetID,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.move(ids, targetID);
	}

	/**
	 * 分页查询
	 * 
	 * @param first
	 * @param limit
	 * @param sort
	 * @param dir
	 * @param moduleID
	 * @param key
	 * @param active
	 * @param code
	 * @param name
	 * @param serverClass
	 * @param serverFunction
	 * @param request
	 * @param response
	 * @param session
	 * @throws Exception
	 */
	@JSON
	@RequestMapping(value = "/system/function/page.json")
	public Page page(
			@RequestParam(value = "first", defaultValue = "0") int first,
			@RequestParam(value = "limit", defaultValue = "20") int limit,
			@RequestParam(value = "sort", required = false) String sort,
			@RequestParam(value = "dir", required = false) String dir,
			@RequestParam(value = "noModuleID", required = false) String noModuleID,
			@RequestParam(value = "moduleID", required = false) String moduleID,
			@RequestParam(value = "key", required = false) String key,
			@RequestParam(value = "active", required = false) String active,
			@RequestParam(value = "code", required = false) String code,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "serverClass", required = false) String serverClass,
			@RequestParam(value = "serverFunction", required = false) String serverFunction,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		Map<String, Object> conditions = new HashMap<String, Object>();

		if (key != null) {
			key = new StringBuffer("%").append(key).append("%").toString();
			conditions.put("key", key);
		}

		if (active != null)
			conditions.put("active", Boolean.parseBoolean(active));

		if (moduleID != null)
			conditions.put("moduleID", moduleID);

		if (code != null) {
			code = new StringBuffer("%").append(code).append("%").toString();
			conditions.put("code", code);
		}
		if (name != null) {
			name = new StringBuffer("%").append(name).append("%").toString();
			conditions.put("name", name);
		}
		if (serverClass != null) {
			serverClass = new StringBuffer("%").append(serverClass).append("%")
					.toString();
			conditions.put("serverClass", serverClass);
		}
		if (serverFunction != null) {
			serverFunction = new StringBuffer("%").append(serverFunction)
					.append("%").toString();
			conditions.put("serverFunction", serverFunction);
		}

		return bean.page(first, limit, sort, dir, conditions, null);
	}

	@JSON
	@RequestMapping(value = "/system/function/treeGrid.json")
	public List<ModuleBusinessFunctionTree> treeGrid(@RequestParam(value = "parentID") String parentID,
			@RequestParam(value = "rootID", required = false) String rootID,
			@RequestParam(value = "roleID", required = false) String roleID,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		Map<String, Object> conditions = new HashMap<String, Object>();

		if (parentID != null && !"module_function_root".equals(parentID))
			conditions.put("parentID", parentID);

		if (rootID != null)
			conditions.put("rootID", rootID);

		if (roleID != null)
			conditions.put("roleID", roleID);

		Context context = (Context) session.getAttribute("context");
		String[] roleIDs = context.getRoleIDs();
		if (roleIDs != null)
			conditions.put("roleIDs", roleIDs);

		return bean.treeGrid(conditions, null);
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(BusinessFunction.class, new JSONEditor(
				BusinessFunction.class));
	}
}
